import mdKatex from "@traptitech/markdown-it-katex"
import hljs from "highlight.js"
import "highlight.js/scss/ir-black.scss"
import MarkdownIt from "markdown-it"
import "./chat.scss"
import { ElMessage } from "element-plus"

export default function useMarkdown() {
  const copyCode = (copyButton: any) => {
    const codeBlock = copyButton.parentNode.nextSibling.querySelector("code")
    const codeText = codeBlock.innerText

    // 生成文本域，用于装饰代码块
    const textareaDom = document.createElement("textarea")
    textareaDom.value = codeText
    document.body.appendChild(textareaDom)
    textareaDom.select()
    document.execCommand("copy")
    ElMessage({
      type: "success",
      message: "复制成功"
    })
    document.body.removeChild(textareaDom)
  }

  window.copyCode = copyCode

  const highlightBlock = (str: any, lang: string) => {
    return `<pre class="pre-code-box"><div class="pre-code-header"><div class="code-block-header__lang">${lang}</div><div class="code-block-header__copy" onclick="copyCode(this)"><img class="copy-img" src="https://lehuopai-1311286543.cos.ap-guangzhou.myqcloud.com/img/page-xm/copy.png" alt="" /> Copy code</div></div><div class="pre-code"><code class="hljs code-block-body ${lang}">${str}</code></div></pre>`
  }

  const mdi = new MarkdownIt({
    linkify: true,
    highlight(code, language) {
      const validLang = !!(language && hljs.getLanguage(language))
      if (validLang) {
        const lang = language ?? ""
        return highlightBlock(hljs.highlight(lang, code, true).value, lang)
      }
      return highlightBlock(hljs.highlightAuto(code).value, "")
    }
  })
  mdi.use(mdKatex, { blockClass: "katexmath-block rounded-md", errorColor: " #cc0000" })

  const getMdiText = (value: any) => {
    if (value) {
      // 匹配 Markdown 表格的正则表达式
      const tableRegex = /\|.*\|\n\|(?:-+:|:-+:|:-+|:--)*\|\n(?:\|.*\|\n)+/gm

      if (value && value.match(tableRegex)) {
        // 渲染 Markdown 表格的代码
        return renderMarkdownTable(value)
      } else {
        return mdi.render(value)
      }
    }
  }

  const renderMarkdownTable = (value: any) => {
    const rows = value.split("\n")
    let headerRow = ""
    let alignRow = ""
    let bodyRows = ""

    // 解析表头、对齐方式和表格内容
    rows.forEach((row: any, index: number) => {
      if (index === 0) {
        headerRow = row.replace(/\|/g, "").trim()
        alignRow = rows[index + 1].replace(/\|/g, "").replace(/-/g, "").trim()
      } else if (index > 1) {
        // @ts-ignore
        const cells = row.split("|").map((cell) => cell.trim())
        if (cells.length > 1) {
          // @ts-ignore
          const bodyRow = cells.reduce((acc, cell, idx) => {
            const align =
              alignRow[idx] === ":" ? "text-align: center;" : alignRow[idx] === "-" ? "" : "text-align: left;"
            return acc + `<td style="${align}">${cell}</td>`
          }, "")
          bodyRows += `<tr>${bodyRow}</tr>`
        }
      }
    })

    // 拼接表格的 HTML 结构
    const tableHtml = `
      <table>
        <thead><tr>${headerRow.split(" ").reduce((acc, h) => acc + `<th>${h}</th>`, "")}</tr></thead>
        <tbody>${bodyRows}</tbody>
      </table>
  `

    return tableHtml
  }

  return { getMdiText }
}
